import {
    ATTR, TEXT,REPLACE,REMOVE
} from './patchType'

let patches = {};
let vnIndex = 0;

function domDiff(oldVDom,newVDom){
    let index = 0;
    vNodeWalk(oldVDom,newVDom,index);
    return patches;
}

function vNodeWalk(oldNode,newNode,index){
    let vnPath = [];
    if(!newNode){
        vnPath.push({
            type:REMOVE,
            index
        })
    }else if(typeof oldNode ==='string'&&typeof newNode ==='string'){
        if(oldNode!==newNode){
            vnPath.push({
                type:TEXT,
                text:newNode
            })
        }
    }else if(oldNode.type === newNode.type){
        const attrPath = attrsWalk(oldNode.props,newNode.props)
        if(Object.keys(attrPath).length>0){
            vnPath.push({
                type:ATTR,
                attrs:attrPath
            })
        }
        childrenWalk(oldNode.children,newNode.children);
    }else{
        vnPath.push({
            type:REPLACE,
            newNode
        })
    }

    if(vnPath.length>0){
        patches[index] = vnPath;
    }
}

function attrsWalk(oldAttrs,newAttrs){
    let attrPath = {};
    // 修改属性
    for(let key in oldAttrs){
        if(oldAttrs[key] !== newAttrs[key]){
            attrPath[key] = newAttrs[key];
        }
    }
    // 新增属性
    for(let key in newAttrs){
        if(!oldAttrs.hasOwnProperty[key]){
            attrPath[key] = newAttrs[key];
        }
    }
    return attrPath;
}

function childrenWalk(oldChildren,newChildren){
    oldChildren.map((c,idx)=>{
        vNodeWalk(c,newChildren[idx],++vnIndex)
    })
}


export default domDiff;
